<?php 

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die();
 
jimport( 'joomla.application.component.model' );

class ShopModelGoods extends JModel
{
    var $_data;
    var $_pages;
 
    function _buildQuery($category,$search) //  строим запрос исходя из фильтров
    {
        
        if (isset($_REQUEST['non_published'])) $non_published = "AND published = '0'";
        else $non_published = '';
        if (isset($_REQUEST['non_sklad'])) $non_sklad = "AND ".(isset($_REQUEST['yes_sklad'])?'(':'')."sklad_sum = '0'";
        else $non_sklad = '';
        if (isset($_REQUEST['yes_sklad'])) 
            $yes_sklad = (isset($_REQUEST['non_sklad'])?'OR':'AND')." sklad_sum = '1'".(isset($_REQUEST['non_sklad'])?')':'');
        else $yes_sklad = '';
        if ($non_published != '' || $non_published != '' || $non_published != '')
            $add_where = 'WHERE 1 ';
        else $add_where = '';
        //printu($non_published,'$non_published');
        if(is_numeric($category))
            if($search != '')
                $query = ' SELECT * FROM #__shop_prod
                WHERE cat_id='.$category.' AND
                    ((locate("'.$search.'",name)>0) OR (locate("'.$search.'",articul)>0))
                    '.$non_published.'
                    '.$non_sklad.'
                    '.$yes_sklad.'
                ORDER BY id ASC '.$limit;
            else
                $query = ' SELECT * FROM #__shop_prod
                           WHERE cat_id='.$category.' '.$non_published.' '.$non_sklad.' '.$yes_sklad.' ORDER BY id ASC '.$limit ;
        else
            if($search != '')
                $query = ' SELECT * FROM #__shop_prod
                WHERE (locate("'.$search.'",name)>0) OR (locate("'.$search.'",articul)>0)
                '.$non_published.'
                '.$non_sklad.'
                '.$yes_sklad.'
                ORDER BY id ASC '.$limit ;
            else
                $query = ' SELECT * FROM #__shop_prod '.$add_where.' 
                    '.$non_published.'
                    '.$non_sklad.'
                    '.$yes_sklad.'
                 ORDER BY id ASC '.$limit ;
        //printu($query,'$query');
        return $query;
    }
	function getPages()
	{
		return $this->_pages;
	}

    function getData()
    {
		
		$category = JRequest::getVar('cat_id',0);
		$page = JRequest::getVar('page',1,'int');
		if($page<=0)
			$page=1;
		$query = "SELECT * FROM #__shop_categories WHERE id =$category";// проверяем категорию
		$this->_db->setQuery( $query );
		
		
		if($this->_db->loadResult() == null)
			$category = true;
		
		$search = JRequest::getVar('search');
        if (empty( $this->_data ))
        {
			$db = & JFactory::getDBO();
            $query = $this->_buildQuery($category,$search);
			$this->_db->setQuery( $query );
			$this->_db->query();
			$this->_pages = $this->_db->getNumRows();
			if($page < $this->_pages) 
				$limit = 'LIMIT '.(($page-1)*30).',30 ';
			else
			{
				$limit = 'LIMIT 0,30 ';
				$page=1;
			}
			$query .= $limit;
			$this->_data = $this->_getList($query);
			
						
			if(is_array($this->_data))
				foreach($this->_data as $k=>$category)
				{
					
					
					$query = "SELECT * FROM #__shop_categories WHERE id=$category->cat_id";
					$this->_db->setQuery( $query );
					$cat_name = $this->_db->loadObject();
					$this->_data[$k]->cat_id = $cat_name->name; // получаем название категории , в которой состоит конкретный товар
				}
			
        }
 
        return $this->_data;
    }
	
	function delete($id)
	{	
		if (!$id || !is_array($id)) {
            return false;
        }
		$query = 'SELECT * FROM #__shop_prod WHERE id IN ('.implode(',', $id).')';
		$this->_db->setQuery($query);
		if ($this->_db->loadResult() != null)
		{
			$goods = $this->_db->loadObjectList();
			foreach($goods as $good)
			{
				if($good->image != '')
					@ unlink(JPATH_SITE . '/components/com_shop/images' . DS . $good->image);
			}
			// удаляем поля добавленые для удаляемых товаров
			$query = 'DELETE FROM #__shop_fields_values WHERE object_id IN ('.implode(',', $id).')';
			$this->_db->setQuery($query);
			$this->_db->query();
			$query = 'DELETE FROM #__shop_prod WHERE id IN ('.implode(',', $id).')';
			$this->_db->setQuery($query);
			$this->_db->query();
			return true;
		}
		return false;
	}
	
}
?>